import json
import time

from myapp import models
from myapp.utils import getPublicData
from myapp.utils.getPublicData import monthList, getAllUsers


def getNowTime():
    timeFormat = time.localtime()
    year = timeFormat.tm_year
    month = timeFormat.tm_mon
    day = timeFormat.tm_mday
    return year, monthList[month-1], day


def getPageData():
    userTotal = models.Users.objects.count()
    jobs = models.JobInfo.objects.all()
    jobTotal = len(jobs)

    highestEducational = ''
    educationalWeight = 9
    highestSalary = 0
    highestSalaryMonth = 0

    citys = {}
    for j in jobs:
        if j.pratice != 0:
            continue

        if citys.get(j.address, -1) == -1:
            citys[j.address] = 1
        else:
            citys[j.address] += 1

        salary = int(int(json.loads(j.salary)[1]) / 1000)
        if salary > highestSalary:
            highestSalary = salary

        if int(j.salaryMonth) > highestSalaryMonth:
            highestSalaryMonth = int(j.salaryMonth)

        for k, v in getPublicData.educations.items():
            if k == j.educational:
                if v < educationalWeight:
                    educationalWeight = v
                    highestEducational = k

    citys = sorted(citys.items(), key=lambda x: x[1], reverse=True)[:3]
    hotCity = [k for k, v in citys]
    hotCity = ', '.join(hotCity) if len(hotCity) > 0 else ''

    result = {
        'jobTotal': jobTotal,
        'userTotal': userTotal,
        'highestEducational': highestEducational,
        'highestSalary': highestSalary,
        'highestSalaryMonth': highestSalaryMonth,
        'hotCity': hotCity
    }
    return result


# 获取用户创建时间
def getUserCreateTime():
    lists = []

    try:
        users = getAllUsers()
        data = {}
        for user in users:
            ctime = str(user.createTime)
            if data.get(ctime, -1) == -1:
                data[ctime] = 1
            else:
                data[ctime] += 1

        for key, value in data.items():
            lists.append({
                'name': key,
                'value': value
            })
    except Exception as err:
        print(f'--- err: {err}')

    return lists


# 获取采集数据
def getSpiderData():
    jobs = models.JobInfo.objects.all()


    tempData = {}
    sortFn = ''
    result = list(sorted(tempData.items(), key=sortFn, reverse=False))

    def mapFn(item):
        item = list(item)
        item.append(round(item[1] / len(jobs), 3))
        return item

    result = list(map(mapFn, result))
    return result


# 获取最新用户信息
def getLatestUserInfo():
    lists = []

    try:
        users = getAllUsers()[:10]
        for index, user in enumerate(users):
            lists.append({
                'index': index+1,
                'name': user.username,
                'password': user.password,
                'createTime': user.createTime
            })
        pass
    except Exception as err:
        print(f'-- err: {err}')

    return lists


def getJobsInfo():
    jobs = models.JobInfo.objects.all()

    for j in jobs:
        j.salary = json.loads(j.salary)[1]

        workTag = json.loads(j.workTag)
        if len(workTag) >= 2:
            j.workTag = ' / '.join(workTag)
        elif len(workTag) == 1:
            j.workTag = workTag[0]
        else:
            j.workTag = ''

        companyTag = j.companyTags
        if companyTag == '无':
            j.companyTags = ''
        else:
            companyTag = json.loads(j.companyTags)
            if len(companyTag) > 1:
                j.companyTags = ', '.join(companyTag)
            else:
                j.companyTags = companyTag[0]

        if j.companyPeople == '[0, 10000]':
            j.companyPeople = '10000人以上'
        else:
            people = json.loads(j.companyPeople)
            j.companyPeople = '-'.join([str(p) for p in people])

    return jobs[:10]
